package org.visionlibrary.image.filters.dithering;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.model.AbstractFilter;


public class OrderedDithering extends AbstractFilter {
	protected int[][] thresholdMatrix = { { 0, 32, 8, 40, 2, 34, 10, 42 },
			{ 16, 48, 24, 58, 18, 50, 26, 58 },
			{ 4, 36, 12, 44, 6, 38, 14, 46 },
			{ 20, 52, 28, 60, 22, 54, 30, 62 },
			{ 1, 33, 9, 41, 3, 35, 11, 43 },
			{ 17, 49, 25, 57, 19, 51, 27, 59 },
			{ 5, 37, 13, 45, 7, 39, 15, 47 },
			{ 21, 53, 29, 61, 23, 55, 31, 63 } };

	/*
	 * protected int[][] thresholdMatrix = { { 0, 32, 8, 40, 2, 34, 10, 42},
	 * {48, 16, 56, 24, 50, 18, 58, 26}, {12, 44, 4, 36, 14, 46, 6, 38}, {60,
	 * 28, 52, 20, 62, 30, 54, 22}, { 3, 35, 11, 43, 1, 33, 9, 41}, {51, 19, 59,
	 * 27, 49, 17, 57, 25}, {15, 47, 7, 39, 13, 45, 5, 37}, {63, 31, 55, 23, 61,
	 * 29, 53, 21} };
	 */

	public int[][] getThresholdMatrix() {
		return thresholdMatrix;
	}

	public void setThresholdMatrix(int[][] thresholdMatrix) {
		this.thresholdMatrix = thresholdMatrix;
	}

	/*
	 * protected int[][] thresholdMatrix = { {1, 9, 3, 11}, {13, 5,15, 7}, {4,
	 * 12, 2, 10}, {16, 8,14, 6}};
	 */

	public TiledImage applyFilter(TiledImage src, TiledImage dest) {

		int maxX = src.getWidth();
		int maxY = src.getHeight();
		for (int ch = 0; ch < src.getNumBands(); ch++) {
			for (int x = 0; x < maxX; x++)
				for (int y = 0; y < maxY; y++) {
					int val = (src.getSample(x, y, ch) >> 2);
					if (val > thresholdMatrix[x & (thresholdMatrix.length - 1)][y
							& (thresholdMatrix.length - 1)])
						dest.setSample(x, y, ch, 255);
					else
						dest.setSample(x, y, ch, 0);
				}
		}

		return dest;
	}
}
